package com.ankicoo.auth.service.impl;

import com.ankicoo.auth.config.AuthenticationProperties;
import com.ankicoo.auth.entity.AuthUserPO;
import com.ankicoo.auth.mapper.UserMapper;
import com.ankicoo.auth.service.UserService;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Optional;


/**
 * Description: 用户信息处理
 *
 * @author : QCYANG
 * @date : 2021/1/11 9:39
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationProperties authenticationProperties;

    @Override
    public AuthUserPO findUserInfoByUserId(String userId){
        Example example = new Example(AuthUserPO.class);
        example.createCriteria().andEqualTo("userId",userId);
        return userMapper.selectOneByExample(example);
    }

    @Override
    public void save(AuthUserPO user) {
        if (Optional.ofNullable(user.getId()).isPresent()) {
            userMapper.updateByPrimaryKey(user);
        } else {
            encryptPassword(user);
            userMapper.insert(user);
        }
    }

    private void encryptPassword(AuthUserPO user) {
        RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(authenticationProperties.getHashAlgorithmName(), user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()), authenticationProperties.getIterations()).toHex();
        user.setPassword(newPassword);
    }
}
